<template>
  <div style="margin:10px 80px">
    <el-card>
      <el-carousel type="card" height="420px" class="demonstration" :initial-index="0" :interval="1000">
        <el-carousel-item v-for="item in pics" :key="item">
          <img :src="item" alt="">
        </el-carousel-item>
      </el-carousel>
    </el-card>
    <el-card style="margin-top: 20px;height: 400px">
      <el-row>
        <el-col :span="18">
          <el-row style="text-align: center">
            <el-col :span="12">
              <el-image style="height: 300px" :src="currentProduct.pic"></el-image>
            </el-col>
            <el-col :span="4"></el-col>
            <el-col :span="8">
              <h1 style="font-weight: bold">{{ currentProduct.name }}</h1>
              <el-divider></el-divider>
              <h4>{{ currentProduct.subTitle }}</h4>
              <el-divider></el-divider>
              <h6 style="color: gray">{{ currentProduct.brandName }}</h6>
              <el-divider></el-divider>
              <h3 class="cart-font">￥{{ Number(currentProduct.price).toFixed(2) }}</h3>
              <h3 style="margin-left: 248px">
                <i style="margin-left: 10px" @click="changeCollection"
                   :class="!collectionStatus?'el-icon-circle-check':'el-icon-success'">
                  <span style="margin-left: 2px;font-weight: bolder">{{ !collectionStatus ? '收藏' : '已收藏' }}</span>
                </i>
              </h3>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16"></el-col>
            <el-col :span="5">
              <m-button style="width: 160px;height: 50px;line-height: 50px;font-size: 16px"
                        text="加入购物车"
                        @click="addCart" classStyle="main-btn"></m-button>
            </el-col>
            <el-col :span="3">
              <m-button style="width: 160px;height: 50px;line-height: 50px;font-size: 16px"
                        text="现在购买"
                        @click="buyNow" classStyle="default-btn"></m-button>
            </el-col>
            <el-col :span="3">
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="6">
        </el-col>
      </el-row>
    </el-card>
    <el-card>
      <el-divider content-position="left">服务描述</el-divider>
      {{ currentProduct.pdesc }}
    </el-card>
    <el-card style="margin-top: 20px">
      <el-divider content-position="left">服务内容</el-divider>
      <div v-html="currentProduct.content"></div>
    </el-card>
    <el-card>
      <el-divider content-position="left">留言评价</el-divider>
      <el-timeline v-if="productEvaluationList.length>0">
        <el-timeline-item :timestamp="item.gmtCreate" placement="top" v-for="item in productEvaluationList">
          <el-card>
            <div>
              <span>
                 <el-avatar :src="item.memberAvatar"></el-avatar>
              </span>
              <h5><span style="color: #1890ff;font-weight: bolder">
                {{ item.memberNickname === '' ? '匿名' : item.memberNickname }}
                <el-divider direction="vertical"></el-divider>
              </span> 评价于 {{ item.gmtCreate }}
              </h5>
              <el-divider content-position="left">打分</el-divider>
              <h6>
                <el-rate v-model="item.star"></el-rate>
              </h6>
            </div>
            <el-divider content-position="left">评价</el-divider>
            <h4> {{ item.content }}</h4>
            <el-divider content-position="left"></el-divider>
          </el-card>
        </el-timeline-item>
      </el-timeline>
      <el-empty v-else description="正在等待您的一致好评呢~">
      </el-empty>
    </el-card>
  </div>
</template>

<script>
import productApi from '../../api/product'
import { useRouter, useRoute, onBeforeRouteUpdate } from 'vue-router'
import { reactive, toRefs, onMounted, computed } from 'vue'
import MButton from '../../components/MButton.vue'
import { useStore } from 'vuex'
import { getToken } from '../../utils/auth'
import cartItemApi from '../../api/cartItem'
import { ElMessage } from 'element-plus'
import orderEvaluaionApi from '../../api/orderEvaluaion'
import productCollectionApi from '../../api/productCollection'

export default {
  name: 'detail',
  components: {
    MButton
  },
  setup () {
    const router = useRouter()
    const store = useStore()
    const route = useRoute()
    const state = reactive({
      currentProduct: {},
      // 商品的轮播图图片
      pics: [],
      // 当前商品评论列表
      productEvaluationList: [],
      // 收藏状态
      collectionStatus: false
    })
    let productId = route.query.id

    // 获取商品详情
    const getProductInfo = () => {
      productApi.detail(productId).then(res => {
        state.currentProduct = res.data
        let picStr = res.data.albumPics
        if (picStr.indexOf(',') !== -1) {
          state.pics = [...picStr.split(',')]
        } else {
          state.pics = [picStr]
        }
      })
    }
    // 加入购物车
    const addCart = async () => {
      let tempItem = {
        id: state.currentProduct.id,
        name: state.currentProduct.name,
        pic: state.currentProduct.pic,
        price: state.currentProduct.price,
        point: state.currentProduct.point
      }
      // 登录了 会直接存在 会员下  没有登录会存在vuex
      if (getToken()) {
        // console.log('打印的正常:product:', JSON.stringify(item))
        const res = await cartItemApi.saveCart({ productId: tempItem.id })
        if (res.code === 200) {
          ElMessage.success(`'${tempItem.name}'加入购物车成功`)
          store.commit('ADD_CART', tempItem)
        }
      } else {
        // 未登录
        store.commit('ADD_CART', tempItem)
        ElMessage.success(`'${tempItem.name}'加入购物车成功`)
      }
    }
    // 现在购买
    const buyNow = async () => {
      let tempItem = {
        id: state.currentProduct.id,
        name: state.currentProduct.name,
        pic: state.currentProduct.pic,
        price: state.currentProduct.price,
        point: state.currentProduct.point
      }
      // 登录了 会直接存在 会员下  没有登录会存在vuex
      if (getToken()) {
        // console.log('打印的正常:product:', JSON.stringify(item))
        const res = await cartItemApi.saveCart({ productId: tempItem.id })
        if (res.code === 200) {
          store.commit('ADD_CART', tempItem)
        }
      } else {
        // 未登录
        store.commit('ADD_CART', tempItem)
      }
      await router.push('/checkout')
    }
    // 获取评价列表
    const getProductEvaluations = () => {
      orderEvaluaionApi.getProductEvaluations(productId).then(res => {
        state.productEvaluationList = res.data
      })
    }
    // 根据商品id查询收藏记录
    const getProductCollection = () => {
      if (getToken()) {
        productCollectionApi.getByProductId(productId).then(res => {
          state.collectionStatus = !!res.data
        })
      }
    }

    // 切换收藏
    const changeCollection = () => {
      if (getToken()) {
        productCollectionApi.changeCollection({ productId: productId }).then(res => {
          if (state.collectionStatus === false) {
            state.collectionStatus = true
            ElMessage.success('收藏成功')
          } else {
            state.collectionStatus = false
            ElMessage.success('取消收藏成功')
          }
        })
      } else {
        router.push('/login')
      }
    }
    //-----------------
    onMounted(() => {
      getProductInfo()
      getProductEvaluations()
      getProductCollection()
    })

    return {
      addCart,
      buyNow,
      changeCollection,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped lang="scss">
.image {
  width: 100%;
  display: block;
}

.cart-font {
  color: red;
  font-weight: bolder;
  font-size: 15px;
}
</style>
